﻿(function(window){

var ImagesMuLazy = $$OBEA.wrapper(function(options){
	this._init(options);
	if(this.isFinish()) return;
	this._initMode();
	this.resize(true);
}, muLazy);

$$OBEA.extend(ImagesMuLazy.prototype, {
	_init : function(options){
		muLazy.prototype._init.call(this, [[], options]);
		
		
		var opt = this.options;
		this.onLoad = opt.onLoad;
		var attribute = this._attribute = opt.attribute;
		
		var getSrc = opt.getSrc,
			filter = $$OBEA.bind(this._filter, this,
					opt['class'],
					getSrc ? function(img){return getSrc(img);}
						: function(img){return img.getAttribute(attribute) || img.src;},
					opt.holder	
				);
		this._elems = $$OBEA.filter(
			opt.images || this._container.getElementsByTagName('img'), filter
		);
		
		this._hasAttribute = $$OBEA.browser.ie6 || $$OBEA.browser.ie7
			? function(img){return attribute in img;}
			: function(img){return img.hasAttribute(attribute);};
		
	},
	
	_setOptions : function(options){
		return muLazy.prototype._setOptions.call(this, $$OBEA.extend({
			images : undefined,
			attribute : '_lazysrc',
			holder : '',
			'class' : '',
			getSrc : undefined,
			onLoad : function(){}
		}, $$OBEA.extend(options, {
			onLoadData : this._onLoadData
		})));
	},
	
	_filter : function(className, getSrc, holder, img){
		if(className && (' ' + img.className + ' ').indexOf(' ' + className + ' ') == -1)
			return false;
			
		var src = getSrc(img);
		
		if(!src)
			return false;
			
		if(src == img.src){
			if(img.complete || $$OBEA.browser.chrome || $$OBEA.browser.safari)
				return false;
			img.removeAttribute('src');
		}
		
		if(holder){
			img.src = holder;
		}
		
		img.setAttribute(this._attribute, src);
		return true;
	},
	
	_onLoadData : function(img){
		var attribute = this._attribute;
		if(this._hasAttribute(img)){
			img.src = img.getAttribute(attribute);
			img.removeAttribute(attribute);
			this.onLoad(img);
		}
	}
	
});

window.ImagesMuLazy = ImagesMuLazy;

})(window)